package com.wzy.orderSystem.service.impl;

import com.wzy.orderSystem.dao.FoodDao;
import com.wzy.orderSystem.pojo.user;
import com.wzy.orderSystem.service.opUser;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

public class opUserImpl implements opUser {
    @Override
    public ArrayList<user> selectById(int id) throws SQLException {
        ArrayList<user> users = new ArrayList<>();
        ResultSet resultSet = null;
        try {
            String sql = "SELECT * FROM `user` WHERE id = ?";
            Object[] obj = {id};
            resultSet = FoodDao.selectByArgs(sql, obj);
            while(resultSet.next()){
                user user = new user();
                int userId = resultSet.getInt(1);
                String userName = resultSet.getString(2);
                String password = resultSet.getString(3);
                String phone = resultSet.getString(4);
                String nickName = resultSet.getString(5);
                String userState = resultSet.getString(6);
                Date nowLogin = resultSet.getDate(7);
                Date lastLogin = resultSet.getDate(8);
                String address = resultSet.getString(9);

                user.setId(userId);
                user.setUsername(userName);
                user.setPassword(password);
                user.setNowLogin(nowLogin);
                user.setLastLogin(lastLogin);
                user.setPhone(phone);
                user.setNickName(nickName);
                user.setUserState(userState);
                user.setUserAddress(address);

                users.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            resultSet.close();
        }
        return users;
    }

    @Override
    public int updateById(int id, String password) {
        int rows = 0;
        String sql = "UPDATE `user` SET password=? WHERE id=?";
        Object[] obj = {password,id};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }

    @Override
    public int deleteById(int id) {
        int rows = 0;
        String sql = "DELETE FROM `user` WHERE id=?";
        Object[] obj = {id};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }

    @Override
    public int insert(int id, String username, String password, String phone, String nickName, String userState, Date nowLogin, Date laseLogin, String address) {
        int rows = 0;
        String sql = "INSERT INTO `orderfood`.`user` (`id`, `user_name`, `password`, `phone`, `nicname`, `user_state`, `now_login`, `last_login`, `user_address`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] obj = {id,username,password,phone,nickName,userState,new Timestamp(nowLogin.getTime()),new Timestamp(laseLogin.getTime()),address};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }
}
